package com.jfsnpm.plugin.viewoffice;

import java.io.File;






import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
/**
 * 接受WOPI client服务器的相关请求
 * @author 天为之殇
 *
 */

public class ViewOfficeController extends Controller {
	@Clear
	public void view(){
		String fileid = getPara("fileid");
		if(fileid==null || "".equals(fileid)){
			renderText("文件不存在！");
			return;
		}
		String file_ext = Db.findById("pm_file", fileid).getStr("type");
		
		
		String clientUrls = ViewOffice.getWOPIClientURL(file_ext.toLowerCase());
		String clientUrl = clientUrls.substring(0, clientUrls.indexOf("?"));
		String wopiserver = getRequest().getScheme()+"://"+
							getRequest().getServerName()+":"+
							getRequest().getServerPort()+"/"+
							getRequest().getContextPath();
		if(wopiserver.endsWith("/")){
			wopiserver = wopiserver + "wopi/files/"+fileid;
		}else{
			wopiserver = wopiserver + "/" + "wopi/files/"+fileid;
		}
		String wopiurl = clientUrl+"?WOPISrc="+wopiserver/*+"&access_token=ok"*/;
		redirect(wopiurl);
	}
	
	
	
	@Clear
	public void files(){
		String fileID = getPara(3);
		String contents = getPara(4);
		//String access_token = getPara("access_token");
		//System.out.println("****fileID****:"+fileID);
		Record rd = Db.findById("pm_file", fileID);
		if("contents".equals(contents)){
			//返回文件流
			File file = new File(rd.getStr("path"));
			if(file.exists()){
				renderFile(file);
				return;
			}
			renderText("File get ERROR!");
		}else{
			//返回文件信息
			//System.out.println("****path****:"+rd.getStr("path"));
			File file = new File(rd.getStr("path"));
			if(file.exists()){
				String BaseFileName = rd.getStr("name")+"."+rd.getStr("type");
				String OwnerId = rd.getStr("update_user");
				String Size = new Long(file.length()).toString();
				String SHA256 = ViewOffice.getFileSHA256(file);//"+17lwXXN0TMwtVJVs4Ll+gDHEIO06l+hXK6zWTUiYms="
				String Version = rd.getStr("ver");
				String json = "{ \"BaseFileName\": \""+BaseFileName+"\", \"OwnerId\": \""+OwnerId+"\", \"Size\": \""+Size+"\", \"SHA256\": \""+SHA256+"\", \"Version\": \""+Version+"\" } ";
				renderJson(json);
				return;
			}
			renderText("File get ERROR!");
		}
		
	}
	
}
